/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package tpgen.grammar;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 *
 * @author shanki
 */
public class Repeat implements Symbol {
    private Symbol symbol;
    private boolean emptyAllowed;
    private double prop;
    
    public Repeat(Symbol symbol, boolean emptyAllowed, double prop) {
        this.symbol         = symbol;
        this.emptyAllowed   = emptyAllowed;
        this.prop           = prop;
    }

    @Override
    public boolean isUsable() {
        return emptyAllowed == true || symbol.isUsable();
    }        

    @Override
    public Collection<Symbol> expand(Context context) {
        List<Symbol> symbols    = new ArrayList<Symbol>();
        
        if (emptyAllowed == false) {
            symbols.add(symbol);
        }
        
        if (symbol.isUsable()) {        
            while(context.nextDouble() <= prop) {
                symbols.add(symbol);
            }
        }
        
        return symbols;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj instanceof Repeat) {
            Repeat other = (Repeat)obj;
            
            return  this.symbol.equals(other.symbol) &&
                    this.emptyAllowed == other.emptyAllowed &&
                    this.prop == other.prop;
        } else {
            return false;
        }
    }

    @Override
    public int hashCode() {
        int hash = 7;
        hash = 83 * hash + (this.symbol != null ? this.symbol.hashCode() : 0);
        hash = 83 * hash + (this.emptyAllowed ? 1 : 0);
        hash = 83 * hash + (int) (Double.doubleToLongBits(this.prop) ^ (Double.doubleToLongBits(this.prop) >>> 32));
        return hash;
    }

    @Override
    public String toString() {
        return "/rep/";
    }

    @Override
    public String toUserString() {
        return "";
    }
    
}
